import { loginAPI } from "@/apis/user";
import { UserDataType, UserType } from "@/types/user";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useCartStore } from "./cart";
import { mergeCartAPI } from "@/apis/cart";

// 管理用户信息
export const useUserStore = defineStore('user', () => {
    // 用户登录信息
    const userData = ref<UserDataType>();

    // 用户登录状态
    const isLogin = computed(() => !!userData.value?.token);

    const cartStore = useCartStore();

    // 用户登录验证
    const verifyUserData = async (data: UserType) => {
        const response = await loginAPI(data);
        userData.value = response.data.result;
        // 合并购物车
        await mergeCartAPI(cartStore.cartList.map(good => ({ skuId: good.skuId, selected: `${good.selected}`, count: good.count })));
        cartStore.getCartList();
    };

    // 注销登录
    const clearUserData = () => {
        userData.value = void 0;
        // 清空购物车缓存
        cartStore.clearCart();
    };

    return { userData, isLogin, verifyUserData, clearUserData };
}, { persist: true });
